package com.freak.kotlinfitnessserver.bt

import android.bluetooth.BluetoothServerSocket
import com.freak.kotlinfitnessserver.util.ByteUtil
import com.freak.kotlinfitnessserver.util.LogUtil
import java.io.DataInputStream

class RythfloSspBluetoothServer(bluetoothListener: BluetoothListener) :
    BaseBluetooth(bluetoothListener) {

    companion object {
        const val TAG: String = "RythfloSspBluetoothServer"
    }

    private var mSSocket: BluetoothServerSocket? = null

    override fun readMessage(dataInputStream: DataInputStream) {
        val byteArray = ByteArray(256)
        // 读入缓冲区的总字节数，如果由于已到达流的末尾而没有更多数据，则返回-1。
        var readStatusOrLength: Int
        while (dataInputStream.read(byteArray)
                .also { readStatusOrLength = it } != -1
        ) {
            LogUtil.i(TAG, "read length = $readStatusOrLength")
        }
        val result: ByteArray = byteArray.copyOfRange(0, readStatusOrLength)
        LogUtil.i(TAG, "result hex string = ${ByteUtil.bytesToHexString(result)}")
    }

    override fun init() {
        super.init()
        startListenConnect()
    }

    private fun startListenConnect() {
        try {
            // 加密传输，Android强制执行配对，弹窗显示配对码
            // mSSocket = adapter.listenUsingRfcommWithServiceRecord(TAG, SPP_UUID)

            // 明文传输(不安全)，无需配对
            mSSocket = mBluetoothAdapter!!.listenUsingInsecureRfcommWithServiceRecord(TAG, SPP_UUID)
            // 监听连接
            val socket = mSSocket!!.accept()
            // 关闭监听，只连接一个设备
            mSSocket!!.close()
            // 循环读取
            startLoopRead(socket)
        } catch (e: Exception) {
            LogUtil.e(TAG, "startListenConnect Exception $e")
            close()
        }
    }
}